import React, { Fragment } from 'react';
import {
  View,
  StyleSheet,
  ScrollView,
  BackHandler,
  NativeModules,
  TouchableOpacity,
  Text, Linking,
  Switch,
  SafeAreaView
} from 'react-native';
import { BackImageOn, msg, Button } from '@/common';
import {
  mainBgColorLightGray,
  fontColorBlack,
  mainBgColorWhite,
  px2dp,
  fontColorCoffee,
  isAndroid, screenWidth
} from '@/styles';
import { uploadImage } from '@/config';
import supply from '@/api/supply';
import DriveLicense from './components/drive-license';
import TransportLicense from './components/transport-license';
import InsuranceCard from './components/insurance-card';
import ChooseAgreement from './components/choose-agreement';
import CertSteps from './components/cert-steps';
import FeedBackDriverCer from './components/driver-cer-feedback';
import AddTruck from '../add-truck';
import GuaDriveLicense from './components/gua-drive-license';
import GuaTransportLicense from './components/gua-transport-license';
import GuaInsuranceCard from './components/gua-insurance-card';
import AxesNumInput from './components/axes-num-input';

const { Submit } = Button;

/**
 * @author kanglang
 * @description 车辆认证
 * @createDate 2020/8/27
 *
 */
export default class TruckCert extends React.Component {
    static navigationOptions = ({ navigation }) => ({
      headerLeft: (
        <BackImageOn onClick={() => {
          const { onBackAndroid } = navigation.state.params;
          onBackAndroid();
        }}
        />

      ),
      headerStyle: {
        borderBottomWidth: 0,
        borderBottomColor: '"#f5f5f5',
        backgroundColor: '#f5f5f5',
        elevation: 0,
      },
    });

    constructor(props) {
      super(props);
      const { navigation } = this.props;
      const state = navigation.state || {};
      const params = state.params || {};
      const { type, data, routerFrom } = params;
      this.state = {
        checked: true,
        cooperateType: '',
        truckType: '',
        hideSelectAlert: false,
        transportation: '',
        sourceType: [],
        licensefrontPhotoId: '', // 行驶证正页正面
        licenseBackPhotoId: '', // 行驶证正页反面
        licenseSecondFrontPhotoId: '', // 行驶证副业正面
        licenseSecondBackPhotoId: '', // 行驶证副业反面
        transportionPhotoFrontId: '', // 道路运输正面图片
        transportionPhotoBackId: '', // 道路运输反面图片
        agentFrontPhotoId: '', // 代理证反面
        agentBackPhotoId: '', // 代理证反面
        insuranceFrontPhoneId: '', // 保险卡正面
        insuranceBackPhoneId: '', // 保险卡反面
        carPersonPhotoId: '', // 人车照片
        cooperationAgreementId: '', // 合作协议
        certificationState: null, // 认证状态
        contactSate: null, // 签约状态
        isEquipment: null, // 安装状态
        reason: null, // 拒绝原因
        carNo: null, // 车牌号
        carId: null, // 车辆id

        type, // add 新增 view 查看
        data,
        isGua: false, // 是否有挂车,
        guaLicensefrontPhotoId: '',
        guaLicenseBackPhotoId: '',
        guaLicenseSecondFrontPhotoId: '',
        guaLicenseSecondBackPhotoId: '',
        guaTransportionPhotoFrontId: '',
        guaTransportionPhotoBackId: '',
        guaAgentFrontPhotoId: '',
        guaAgentBackPhotoId: '',
        guaInsuranceFrontPhoneId: '',
        guaInsuranceBackPhoneId: '',
        axisNumber: '',
        guaAxisNumber: '',
        routerFrom,
        tempRouters: []
      };
    }

    componentDidMount() {
      const { navigation } = this.props;
      navigation.setParams({
        onBackAndroid: this.onBackAndroid,
      });
      if (Platform.OS == 'android') {
        BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
      }
      if (Platform.OS === 'ios') {
        NativeModules.BridgeManager.iOSIQKeyaboard(true);
      }
      this.getSignStatus();
    }

    // 获取签订状态
    getSignStatus = () => {
      const { data } = this.state;
      supply.getCarProgress({ carId: data && data.id }).then(res => {
        if (res.success) {
          let myData = res.data;
          myData.cooperationType = (data && data.cooperationType) || '';
          let newData = Object.assign(myData, data);
          console.log('==========data');
          console.log(data);
          this.setState({ data: newData });
        }
      });
    }

    componentWillUnmount() {
      if (Platform.OS == 'android') {
        BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
      }
      if (Platform.OS === 'ios') {
        NativeModules.BridgeManager.iOSIQKeyaboard(false);
      }
    }

    onBackAndroid = () => {
      const { tempRouters } = this.state;
      tempRouters.pop();
      if (tempRouters.length === 0) {
        msg.emit('router: back');
      }
      this.setState({ tempRouters });
      return true;
    }

    onChecked = (checked) => {
      this.setState({ checked: !checked });
    }

    // 选择图片
    uploadImage = imgType => {
      NativeModules.DataModule.chooseImage((path, imageBase64) => {
        this.IdCardUpload(imgType, path);
      });
    }

    // 上传图片
    IdCardUpload(imgType, path) {
      NativeModules.WindowModule.showLoading();
      uploadImage('upload?dirName=truckCert', path).then(res => {
        console.log(`uploadImage：${JSON.stringify(res)}`);
        if (res.success) {
          this.setState({ [imgType]: res.data.localId }, () => {
            if (imgType == 'licensefrontPhotoId') { // 行驶证正页正面
              this.toCert(res.data.localId, 1, 1);
            } else if (imgType == 'licenseSecondFrontPhotoId') { // 行驶证副业正面
              this.toCert(res.data.localId, 1, 2);
            } else if (imgType == 'transportionPhotoFrontId') { // 道路运输正面图片
              this.toCert(res.data.localId, 1, 3);
            } else if (imgType == 'guaLicensefrontPhotoId') { // 挂车道路运输正面图片
              this.toCert(res.data.localId, 2, 1);
            } else if (imgType == 'guaLicenseSecondFrontPhotoId') { // 挂车道路运输正面图片
              this.toCert(res.data.localId, 2, 2);
            } else if (imgType == 'guaTransportionPhotoFrontId') { // 挂车道路运输正面图片
              this.toCert(res.data.localId, 2, 3);
            }
          });
        } else {
          NativeModules.WindowModule.showWindow({ content: '上传失败，请重试', onlyRightBtn: '1' }, (e) => { });
        }
        NativeModules.WindowModule.dismissLoading();
      }).catch(err => {
        console.log(err);
        NativeModules.WindowModule.dismissLoading();
        // 请求失败
        NativeModules.WindowModule.showWindow({ content: '上传出错，请重试', onlyRightBtn: '1' }, (e) => { });
      });
    }

    // 识别图片
    toCert = (fileId, trailer, type) => {
      const certiParams = {
        fileId,
        trailer,
        type
      };
      supply.ocrCar(certiParams).then(res => {
        if (!res.success) {
          msg.emit('app:tip', { text: res.msg });
          if (trailer == 1) {
            if (type == 1) {
              this.setState({ licensefrontPhotoId: '' });
            } else if (type == 2) {
              this.setState({ licenseSecondFrontPhotoId: '' });
            } else if (type == 3) {
              this.setState({ transportionPhotoFrontId: '' });
            }
          } else if (trailer == 2) {
            if (type == 1) {
              this.setState({ guaLicensefrontPhotoId: '' });
            } else if (type == 2) {
              this.setState({ guaLicenseSecondFrontPhotoId: '' });
            } else if (type == 3) {
              this.setState({ guaTransportionPhotoFrontId: '' });
            }
          }
        }
      });
    }

    // 提交
    toSubmit = () => {
      const {
        checked, licensefrontPhotoId, licenseBackPhotoId, licenseSecondFrontPhotoId,
        licenseSecondBackPhotoId, transportionPhotoFrontId, transportionPhotoBackId,
        agentFrontPhotoId, agentBackPhotoId, insuranceFrontPhoneId, insuranceBackPhoneId,
        guaLicensefrontPhotoId, guaLicenseBackPhotoId, guaLicenseSecondFrontPhotoId,
        guaLicenseSecondBackPhotoId, guaTransportionPhotoFrontId, guaTransportionPhotoBackId,
        guaAgentFrontPhotoId, guaAgentBackPhotoId, guaInsuranceFrontPhoneId, guaInsuranceBackPhoneId,
        isGua, axisNumber, guaAxisNumber, routerFrom
      } = this.state;
      if (!checked) return msg.emit('app:tip', { text: '请先勾选货物运输协议' });
      if (!licensefrontPhotoId) {
        return msg.emit('app:tip', { text: '请重新上传行驶证主页正面' });
      }
      if (!licenseBackPhotoId) {
        return msg.emit('app:tip', { text: '请重新上传行驶证主页背面' });
      }
      if (!licenseSecondFrontPhotoId) {
        return msg.emit('app:tip', { text: '请重新上传行驶证副页正面' });
      }
      if (!licenseSecondBackPhotoId) {
        return msg.emit('app:tip', { text: '请重新上传行驶证副页背面' });
      }
      if (!transportionPhotoFrontId) {
        return msg.emit('app:tip', { text: '请重新上传道路运输证正面' });
      }
      if (!transportionPhotoBackId) {
        return msg.emit('app:tip', { text: '请重新上传道路运输证背面' });
      }
      if (!agentFrontPhotoId) {
        return msg.emit('app:tip', { text: '请重新上传代理证正面' });
      }
      if (!agentBackPhotoId) {
        return msg.emit('app:tip', { text: '请重新上传代理证背面' });
      }
      if (!insuranceFrontPhoneId) {
        return msg.emit('app:tip', { text: '上传货车商业险保单' });
      }
      if (!insuranceBackPhoneId) {
        return msg.emit('app:tip', { text: '上传货车交强险保单' });
      }
      // 挂
      if (isGua && !guaLicensefrontPhotoId) {
        return msg.emit('app:tip', { text: '请重新上传挂车行驶证主页正面' });
      }
      if (isGua && !guaLicenseBackPhotoId) {
        return msg.emit('app:tip', { text: '请重新上传挂车行驶证主页背面' });
      }
      if (isGua && !guaLicenseSecondFrontPhotoId) {
        return msg.emit('app:tip', { text: '请重新上传挂车行驶证副页正面' });
      }
      if (isGua && !guaLicenseSecondBackPhotoId) {
        return msg.emit('app:tip', { text: '请重新上传挂车行驶证副页背面' });
      }
      if (isGua && !guaTransportionPhotoFrontId) {
        return msg.emit('app:tip', { text: '请重新上传挂车道路运输证正面' });
      }
      if (isGua && !guaTransportionPhotoBackId) {
        return msg.emit('app:tip', { text: '请重新上传挂车道路运输证背面' });
      }
      if (isGua && !guaAgentFrontPhotoId) {
        return msg.emit('app:tip', { text: '请重新上传挂车代理证正面' });
      }
      if (isGua && !guaAgentBackPhotoId) {
        return msg.emit('app:tip', { text: '请重新上传挂车代理证背面' });
      }
      if (isGua && !guaInsuranceFrontPhoneId) {
        return msg.emit('app:tip', { text: '上传货车商业险保单' });
      }
      // if (isGua && !guaInsuranceBackPhoneId) {
      //     return msg.emit("app:tip", { text: "请重新上传挂车保险卡/保险单背面" });
      // }
      if (axisNumber <= 0) {
        return msg.emit('app:tip', { text: '请输入车辆轴数' });
      }
      if (isGua && guaAxisNumber <= 0) {
        return msg.emit('app:tip', { text: '请输入挂车车辆轴数' });
      }

      const carParams = {
        carPicture: {
          axisNumber,
          licensefrontPhotoId,
          licenseBackPhotoId,
          licenseSecondFrontPhotoId,
          licenseSecondBackPhotoId,
          transportionPhotoFrontId,
          transportionPhotoBackId,
          agentFrontPhotoId,
          agentBackPhotoId,
          insuranceFrontPhoneId,
          insuranceBackPhoneId,
        }
      };
      if (isGua) {
        carParams.trailerPicture = {
          axisNumber: guaAxisNumber,
          agentBackPhotoId: guaAgentBackPhotoId,
          agentFrontPhotoId: guaAgentFrontPhotoId,
          insuranceBackPhoneId: guaInsuranceBackPhoneId,
          insuranceFrontPhoneId: guaInsuranceFrontPhoneId,
          licenseBackPhotoId: guaLicenseBackPhotoId,
          licenseSecondBackPhotoId: guaLicenseSecondBackPhotoId,
          licenseSecondFrontPhotoId: guaLicenseSecondFrontPhotoId,
          licensefrontPhotoId: guaLicensefrontPhotoId,
          transportionPhotoBackId: guaTransportionPhotoBackId,
          transportionPhotoFrontId: guaTransportionPhotoFrontId
        };
      }
      console.log('============');
      console.log(carParams);
      supply.addCar(carParams).then(response => {
        if (response.success) {
          this.setState({
            type: 'view',
            data: {
              certificationState: '1',
              state: 0
            }
          });
          msg.emit('router: refreshRoute', {
            routeName: 'CarOwnerTruckList',
            routerFrom
          });
        } else {
          if (response.msg) {
            msg.emit('app:tip', { text: response.msg });
          } else {
            msg.emit('app:tip', { text: '认证失败，请重新上传证件' });
          }
        }
      });
    }

    render() {
      const {
        checked,
        licensefrontPhotoId, // 行驶证正页正面
        licenseBackPhotoId, // 行驶证正页反面
        licenseSecondFrontPhotoId, // 行驶证副业正面
        licenseSecondBackPhotoId, // 行驶证副业反面
        transportionPhotoFrontId, // 道路运输正面图片
        transportionPhotoBackId, // 道路运输反面图片
        agentFrontPhotoId, // 代理证反面
        agentBackPhotoId, // 代理证反面
        insuranceFrontPhoneId, // 保险卡正面
        insuranceBackPhoneId, // 保险卡反面
        guaLicensefrontPhotoId,
        guaLicenseBackPhotoId,
        guaLicenseSecondFrontPhotoId,
        guaLicenseSecondBackPhotoId,
        guaTransportionPhotoFrontId,
        guaTransportionPhotoBackId,
        guaAgentFrontPhotoId,
        guaAgentBackPhotoId,
        guaInsuranceFrontPhoneId,
        guaInsuranceBackPhoneId,
        type,
        data,
        isGua,
        axisNumber,
        guaAxisNumber,
        routerFrom,
        tempRouters
      } = this.state;
      return (
        <SafeAreaView>
          <ScrollView
            contentContainerStyle={{ alignItems: 'center', }}
            showsVerticalScrollIndicator={false}
          >
            <View style={styles.container}>
              <CertSteps
                type={type}
                currentData={data}
              />
              {/* TODO:接入流程判断 */}
              <View style={styles.addCerWrap}>
                {
                  type == 'add' &&
                  <View style={{ width: '100%', alignItems: 'center' }}>
                    <>
                      <View style={styles.xmTipBox}>
                        <Text style={styles.xmTips}>请认证您的车辆证照</Text>
                      </View>
                      {/* 行驶证 */}
                      <DriveLicense
                        image1={licensefrontPhotoId}
                        image2={licenseBackPhotoId}
                        image3={licenseSecondFrontPhotoId}
                        image4={licenseSecondBackPhotoId}
                        onImageData={this.uploadImage}
                      />
                      {/* 道路运输证 */}
                      <TransportLicense
                        image5={transportionPhotoFrontId}
                        image6={transportionPhotoBackId}
                        image7={agentFrontPhotoId}
                        image8={agentBackPhotoId}
                        onImageData={this.uploadImage}
                      />
                      {/* 保险卡/保险单 */}
                      <InsuranceCard
                        image9={insuranceFrontPhoneId}
                        image10={insuranceBackPhoneId}
                        onImageData={this.uploadImage}
                      />
                      <AxesNumInput
                        title='轴数'
                        placeholder='必填，请输入轴数'
                        value={axisNumber}
                        keyboardType={isAndroid ? 'numeric' : 'decimal-pad'}
                        onChangeText={(text) => {
                          if (text == 0) {
                            this.setState({ axisNumber: '' });
                          } else if (text > 10) {
                            this.setState({ axisNumber: '10' });
                          } else {
                            this.setState({ axisNumber: text });
                          }
                        }}
                      />

                    </>
                    <>
                      <View style={styles.isGuaSelect}>
                        <Text style={styles.axesLabel}>是否包含挂车</Text>

                        <Switch
                          trackColor={{ flex: 1, false: '#F5F5F5', true: '#BA914A' }}
                          thumbColor='#FFFFFF'
                          ios_backgroundColor='#3e3e3e'
                          onValueChange={this.toggleSwitch}
                          value={isGua}
                        />
                      </View>
                      {
                        isGua &&
                        <View>
                          {/* 挂车行驶证 */}
                          <GuaDriveLicense
                            image1={guaLicensefrontPhotoId}
                            image2={guaLicenseBackPhotoId}
                            image3={guaLicenseSecondFrontPhotoId}
                            image4={guaLicenseSecondBackPhotoId}
                            onImageData={this.uploadImage}
                          />
                          {/* 挂车 道路运输证 */}
                          <GuaTransportLicense
                            image5={guaTransportionPhotoFrontId}
                            image6={guaTransportionPhotoBackId}
                            image7={guaAgentFrontPhotoId}
                            image8={guaAgentBackPhotoId}
                            onImageData={this.uploadImage}
                          />
                          {/* 挂车保险卡/保险单 */}
                          <GuaInsuranceCard
                            image9={guaInsuranceFrontPhoneId}
                            // image10={guaInsuranceBackPhoneId}
                            onImageData={this.uploadImage}
                          />
                          <AxesNumInput
                            title='轴数'
                            placeholder='必填，请输入轴数'
                            value={guaAxisNumber}
                            keyboardType={isAndroid ? 'numeric' : 'decimal-pad'}
                            onChangeText={(text) => {
                              if (text == 0) {
                                this.setState({ guaAxisNumber: '' });
                              } else if (text > 10) {
                                this.setState({ guaAxisNumber: '10' });
                              } else {
                                this.setState({ guaAxisNumber: text });
                              }
                            }}
                          />
                        </View>
                      }
                    </>
                    {/* 《货物运输协议》 */}
                    <ChooseAgreement
                      checked={checked}
                      onChecked={() => this.onChecked(checked)}
                    />
                    <Submit
                      text='提交'
                      onClick={this.toSubmit}
                      boxStyle={styles.btnBoxStyle}
                      btnTextStyle={{
                        fontSize: px2dp(28),
                      }}
                    />

                  </View>
                }
                {type == 'view' && data.certificationState == 1 &&
                <FeedBackDriverCer
                  status={1}
                  title='车辆审核中'
                  desc='工作人员将在3个工作日内给予答复'
                />}
                {type == 'view' && data.certificationState == 3 &&
                <FeedBackDriverCer
                  status={0}
                  title='车辆认证失败'
                  desc={`原因:${data.reason || ''}`}
                  onChange={() => {
                    this.recert();
                  }}
                />}
                {((type == 'view' && data && data.certificationState == 2 && data.state == 1) || (data && data.cooperationType == '解约')) &&
                <AddTruck
                  data={data}
                  customRouters={tempRouters[tempRouters.length - 1]}
                  onChangeAddTruck={this.onChangeAddTruck}
                />}
                {/* {type == 'view' && data && data.certificationState == 2 && data.state == 2 && data.cooperationType != '解约' &&
                                <FeedBackDriverCer
                                    status={1}
                                    title='设备待安装'
                                    subDesc={
                                        <TouchableOpacity
                                            activeOpacity={0.8}
                                            onPress={() => { this.callServicePhone('16687776525') }}
                                        >
                                            <Text>请联系客服人员:
                                    <Text style={{ color: '#2293FF' }}>16687776525</Text>
                                        ，为您的车辆安排OBD设备安装事宜
                                    </Text>
                                        </TouchableOpacity>
                                    }
                                />} */}
              </View>
            </View>
          </ScrollView>
        </SafeAreaView>
      );
    }

    onChangeAddTruck = (obj) => {
      const { tempRouters } = this.state;
      tempRouters.push(obj);
      this.setState({ tempRouters });
    }

    // 选择车辆类型
    chooseTruckType = () => {
      this.setState({ hideSelectAlert: true });
    }

    // 是否需要上传挂车证件照
    toggleSwitch = () => {
      const { isGua } = this.state;
      this.setState({ isGua: !isGua });
    }

    // 重新认证
    recert = () => {
      const { data } = this.state;
      const carId = data ? data.id : '';
      console.log('认证失败的carId-->', carId);
      supply.deleteCar({ carId }).then(res => {
        if (res.success) {
          msg.emit('router: refreshRoute', {
            routeName: 'CarOwnerTruckList',
          });
          this.setState({
            type: 'add',
            data: {
              certificationState: null,
              state: 0
            }
          });
        } else {
          msg.emit('app:tip', { text: res.msg });
        }
      });
    }

    callServicePhone = (phone) => {
      const url = `tel:${phone}`;
      Linking.canOpenURL(url)
        .then((supported) => {
          if (!supported) {
            NativeModules.WindowModule.showWindow(
              {
                content: `您的设备不支持该功能，请手动拨打${phone}`,
                onlyRightBtn: '1',
              },
              (e) => { },
            );
            return;
          }
          return Linking.openURL(url);
        })
        .catch((err) => {
          msg.emit('app:tip', { text: msg });
        });
    };
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: mainBgColorLightGray,
  },
  alertWrap: {
    width: screenWidth,
    marginTop: px2dp(12) * 2
  },
  btnBoxStyle: {
    width: px2dp(640),
    height: px2dp(96),
    borderWidth: 1,
    borderColor: fontColorCoffee,
    borderRadius: px2dp(48),
    marginTop: px2dp(64),
    marginBottom: px2dp(100)
  },
  addCerWrap: {
    borderTopLeftRadius: px2dp(24),
    borderTopRightRadius: px2dp(24),
    overflow: 'hidden',
    alignItems: 'center',
    width: '100%',
    flex: 1,
  },
  axesWrap: {
    width: '100%',
    height: px2dp(100),
    marginTop: px2dp(24),
    flexDirection: 'row',
    backgroundColor: mainBgColorWhite,
    alignItems: 'center'
  },
  axesLabel: {
    marginLeft: px2dp(32),
    marginRight: px2dp(20),
    color: fontColorBlack,
    fontWeight: 'bold'
  },
  axesNumber: {
    flex: 1,
    marginRight: px2dp(32)
  },
  xmTipBox: {
    width: screenWidth,
    backgroundColor: mainBgColorWhite,
    padding: px2dp(32),
    alignItems: 'center'
  },
  xmTips: {
    color: '#343332',
    fontSize: px2dp(40)
  },
  isGuaSelect: {
    flex: 1,
    width: screenWidth,
    flexDirection: 'row',
    backgroundColor: mainBgColorWhite,
    alignItems: 'center',
    justifyContent: 'space-between',
    marginTop: px2dp(24),
    paddingVertical: px2dp(30)
  },
});
